package org.example.springmvc.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.springmvc.component.JWTComponent;
import org.example.springmvc.dox.User;
import org.example.springmvc.exception.Code;
import org.example.springmvc.service.UserService;
import org.example.springmvc.vo.ResultVO;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/")
public class LoginController {
    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final JWTComponent jwtComponent;
    @PostMapping("login")
    public ResultVO login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        User userByAccount = userService.getUserByAccount(user.getAccount());
        if (userByAccount == null || !passwordEncoder.matches(user.getPassword(), userByAccount.getPassword())) {
            return ResultVO.error(Code.LOGIN_ERROR);
        }
        String token=jwtComponent.encode(Map.of("uid",userByAccount.getId(),"role",userByAccount.getRole()));
        response.setHeader("token",token);
        response.setHeader("role",userByAccount.getRole());

        return ResultVO.success(userByAccount);
    }
    @GetMapping("ok")
    public ResultVO getok(){
        return ResultVO.builder()
                .code(200)
                .data("wnhkfdw")
                .build();
    }
    @GetMapping("error")
    public ResultVO geterror(){
        return ResultVO.error(Code.LOGIN_ERROR);
    }
}
